<template>
    <el-dialog :visible.sync="isShow" :title="headerTitle" @close="handleClose" center top="14vh" width="80%" append-to-body :fullscreen="fullscreen">
        <el-form :model="dialogForm" size="small" :disabled="type==3" label-suffix=":" ref="detailForm" :rules="rules" label-width="80px">
            <el-row>
                <el-col :span="6">
                    <!--              计量编号-->
                    <el-form-item :label="$t('mtool.measuringCode')" prop="measuringCode">
                        <el-input :disabled="type !== 1" v-model="dialogForm.measuringCode" @input="(val)=>resetValidate(val)" :placeholder="$t('mtool.measuringHolder')" clearable />
                    </el-form-item>
                </el-col>
                <!-- <el-col :span="6">
                    <el-form-item :label="$t('mtool.standard')" prop="standard">
                        <el-select style="width:100%" v-model="dialogForm.standard" :placeholder="$t('public.selectPl')+$t('mtool.standard')">
                            <el-option v-for="dict in dict.type.NYIQC_STANDARD" :key="dict.value" :label="dict.label" :value="dict.value" />
                        </el-select>
                    </el-form-item>
                </el-col> -->
                <el-col :span="6">
                    <!--              设备名称-->
                    <el-form-item ref="deviceName" :label="$t('mtool.deviceName')" prop="deviceName">
                        <el-input :disabled="type !== 1" v-model="dialogForm.deviceName" :placeholder="$t('public.placeholder',{placeholder: $t('mtool.deviceName')})" clearable />
                        <!-- <el-autocomplete style="width:100%" popper-class="my-autocomplete" v-model="dialogForm.deviceName" value-key="deviceName" :fetch-suggestions="deviceRemoteMethod" :placeholder="$t('public.select_holder',{select_holder: $t('mtool.deviceName')})" @select="handleDeviceSelect">
                            <i class="el-icon-search el-input__icon" slot="suffix">
                            </i>
                        </el-autocomplete> -->
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <!--              量具类型-->
                    <el-form-item :label="$t('mtool.gaugeType')" prop="gaugeType">
                        <el-select style="width:100%" v-model="dialogForm.gaugeType" :placeholder="$t('public.selectPl')+$t('mtool.standard')">
                            <el-option v-for="dict in dict.type.NYIQC_GAUGE_TYPE" :key="dict.value" :label="dict.label" :value="dict.value" />
                        </el-select>
                        <!-- <el-input v-model="dialogForm.gaugeType" clearable disabled size="small" /> -->
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="6">
                    <!--              状态-->
                    <el-form-item :label="$t('mtool.status')" prop="status">
                        <el-select style="width:100%" v-model="dialogForm.status" :placeholder="$t('public.selectPl')+$t('mtool.status')">
                            <el-option v-for="dict in dict.type.NYIQC_STATUS" :key="dict.value" :label="dict.label" :value="dict.value" />
                        </el-select>
                    </el-form-item>
                </el-col>
                <!-- <el-col :span="6">
                    <el-form-item :label="$t('mtool.masStatus')" prop="masStatus">
                        <el-select style="width:100%" v-model="dialogForm.masStatus" :placeholder="$t('public.selectPl')+$t('mtool.masStatus')">
                            <el-option v-for="dict in dict.type.NYIQC_MSA_STATUS" :key="dict.value" :label="dict.label" :value="dict.value" />
                        </el-select>
                    </el-form-item>
                </el-col> -->
                <el-col :span="6">
                    <!--              厂区-->
                    <el-form-item ref="factoryName" :label="$t('mtool.factoryName')" prop="factoryName">
                        <el-autocomplete style="width:100%" popper-class="my-autocomplete" :popper-append-to-body="false" v-model="dialogForm.factoryName" :fetch-suggestions="factoryRemoteMethod" :placeholder="$t('public.select_holder',{select_holder: $t('mtool.factoryName')})" @select="handleFactorySelect">
                            <i class="el-icon-search el-input__icon" slot="suffix">
                            </i>
                            <template slot-scope="{ item }">
                                {{ item.plantName }}
                            </template>
                        </el-autocomplete>
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <!--              存放位置-->
                    <el-form-item :label="$t('mtool.storeLocation')" prop="storeLocation">
                        <el-input v-model="dialogForm.storeLocation" :placeholder="$t('public.inputPl')" clearable size="small" />
                    </el-form-item>
                </el-col>

            </el-row>
            <el-row>
                <el-col :span="6">
                    <!--              数量-->
                    <el-form-item :label="$t('mtool.quantity')" prop="quantity">
                        <el-input v-model="dialogForm.quantity" :placeholder="$t('public.inputPl')" clearable size="small" />
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <!--              型号-->
                    <el-form-item :label="$t('mtool.model')" prop="model">
                        <el-input v-model="dialogForm.model" clearable :placeholder="$t('public.inputPl')" size="small" />
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <!--              制造商-->
                    <el-form-item :label="$t('mtool.maker')" prop="maker">
                        <el-input v-model="dialogForm.maker" clearable :placeholder="$t('public.inputPl')" size="small" />
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <!--            用途-->
                <el-form-item :label="$t('mtool.purpose')" prop="purpose">
                    <el-input v-model="dialogForm.purpose" type="textarea" maxlength="1000" :placeholder="$t('public.inputPl')" clearable />
                </el-form-item>
            </el-row>
            <el-row>
                <!--            设备参数-->
                <el-form-item :label="$t('mtool.deviceParameter')" prop="deviceParameter">
                    <el-input v-model="dialogForm.deviceParameter" type="textarea" maxlength="1000" :placeholder="$t('public.inputPl')" clearable />
                </el-form-item>
            </el-row>
            <el-row>
                <el-col :span="6">
                    <!--             责任人 -->
                    <el-form-item :label="$t('mtool.respName')" prop="respName">
                        <el-input disabled v-if="type == 3" v-model="dialogForm.respUser.name" type="text" />
                        <select-user-dialog v-model="dialogForm.respName" v-else @sendData="(row) => handleRespName(row)" />
                        <!-- <enjoy-select-user :deptId="dialogForm.respDeptment && dialogForm.respDeptment.id" v-else v-model="dialogForm.respUser" @change="handleRespName">
                        </enjoy-select-user> -->
                    </el-form-item>
                </el-col>

                <el-col :span="6">

                    <!--              责任部门-->
                    <el-form-item :label="$t('mtool.respDept')" prop="respDept">
                        <el-input disabled v-model="dialogForm.respDeptment.name" type="text" />
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <!--              使用人-->
                    <el-form-item :label="$t('mtool.employName')" prop="employName">
                        <el-input disabled v-if="type == 3" v-model="dialogForm.employer.name" type="text" />
                        <select-user-dialog v-model="dialogForm.employName" v-else @sendData="(row) => handleEmployName(row)" />
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <!--             计量日期 -->
                    <el-form-item :label="$t('mtool.gaugeTime')" prop="gaugeTime">
                        <el-date-picker v-model="dialogForm.gaugeTime" value-format="yyyy-MM-dd" type="date" @change="handleGaugeTime" :placeholder="$t('public.select_holder',{select_holder: $t('mtool.gaugeTime')})">
                        </el-date-picker>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="6">
                    <!--           到期日期-->
                    <el-form-item :label="$t('mtool.expireTime')" prop="expireTime">
                        <el-date-picker v-model="dialogForm.expireTime" type="date" value-format="yyyy-MM-dd" :picker-options="expireTimeOptions" @change="handleExpireTime" :placeholder="$t('public.select_holder',{select_holder: $t('mtool.expireTime')})">
                        </el-date-picker>
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <!--              资产编号-->
                    <el-form-item :label="$t('mtool.propertyCode')" prop="propertyCode">
                        <el-input v-model="dialogForm.propertyCode" clearable :placeholder="$t('public.inputPl')" size="small" />
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item :label="$t('mtool.remDay')">
                        {{dialogForm.remDay}}
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-form-item :label="$t('mtool.fileAtt')">
                    <file-upload v-model="dialogForm.file" :disabled="type==3" :otherList="picList" ref="incomingFiles" :bizId="dialogForm.id" @change="(fileList)=>picChange(fileList)"></file-upload>
                </el-form-item>
            </el-row>
        </el-form>
        <div slot="footer" class="dialog-footer">
            <el-button @click="$emit('update:visible',false)" icon="el-icon-close" size="small">{{$t('public.cancel')}}</el-button>
            <el-button v-if="type !== 3" type="primary" @click="submitForm" :loading="loading" icon="el-icon-document" size="small">{{$t('public.define')}}</el-button>
        </div>
    </el-dialog>
</template>

<script>
import {listAllGaugeMessage} from '@/api/basic/gaugeMessage'
import {addGauge, modGauge} from '@/api/basic/gauge'
import {listALLFactory} from '@/api/basic/factory'
import EnjoySelectUser from '@/components/EnjoySelectUser'
import EnjoySelectDeptTree from '@/components/EnjoySelectDeptTree'
import FileUploadInput from '@/components/FileUploadInput'
import {geFileByBiz} from '@/api/file/file'
import SelectUserDialog from '@/views/components/SelectUserDialog'

export default {
    name: 'mtool-detial',
    components: {
        EnjoySelectUser,
        EnjoySelectDeptTree,
        FileUploadInput,
        SelectUserDialog,
    },
    dicts: [
        'NYIQC_STANDARD', //标准品 【是，否】
        'NYIQC_STATUS', //状态 【0 再用 1停用 2报废】
        'NYIQC_MSA_STATUS', //MSA状态 【0完成  1未开始  2进行中】
        'NYIQC_GAUGE_TYPE',
    ],
    props: {
        value: {
            type: Object,
        },
        visible: {
            type: Boolean,
            default: false,
        },
        type: [String, Number], //1:新增  2：编辑 3：查看
    },
    watch: {
        value(val) {
            this.dialogForm = { ...val }
            this.dialogForm.respUser = { id: '0', name: val.respName }
            this.dialogForm.respDeptment = { id: '0', name: val.respDept }
            this.dialogForm.employer = { id: '0', name: val.employName }
            if (this.dialogType !== 1) {
                this.geFileByBiz()
            }
        },
    },
    computed: {
        isShow: {
            get() {
                return this.visible
            },
            set() {},
        },
        headerTitle() {
            const { type } = this
            let title = ''
            if (type == 1) {
                title = this.$t('mtool.addHeader')
            }
            if (type == 2) {
                title = this.$t('mtool.editHeader')
            }
            if (type == 3) {
                title = this.$t('mtool.viewHeader')
            }
            return title
        },
    },
    data() {
        return {
            loading: false,
            fullscreen: false,
            deviceOptions: undefined,
            factoryOptions: undefined,
            dialogForm: {},
            picFileList: [],
            picList: [],
            //expireTime 到期日期
            expireTimeOptions: {
                disabledDate(time) {
                    return false
                },
            },

            // 表单校验
            rules: {
                measuringCode: [
                    {
                        required: true,
                        message: '计量编号没有可以填NA',
                        trigger: 'blur',
                    },
                ],
                standard: [
                    {
                        required: true,
                        message: '标准品不能为空',
                        trigger: 'change',
                    },
                ],
                deviceName: [
                    {
                        required: true,
                        message: '设备名称不能为空',
                        trigger: 'change',
                    },
                ],
                factoryName: [
                    {
                        required: true,
                        message: this.$t('formValidation.factoryAreaCannotBeEmpty'),
                        trigger: 'change',
                    },
                ],
                status: [
                    {
                        required: true,
                        message: '状态不能为空',
                        trigger: 'change',
                    },
                ],
                masStatus: [
                    {
                        required: true,
                        message: 'MSA状态不能为空',
                        trigger: 'change',
                    },
                ],
                respName: [
                    {
                        required: true,
                        message: '责任人不能为空',
                        trigger: 'change',
                    },
                ],
                respDept: [
                    {
                        required: true,
                        message: '责任部门不能为空',
                        trigger: 'change',
                    },
                ],
                gaugeTime: [
                    {
                        required: true,
                        validator: (rule, value, callback) => {
                            if (!value)
                                return callback(new Error('计量日期不能为空！'))
                            if (this.dialogForm.expireTime) {
                                let t = new Date(
                                    this.dialogForm.expireTime
                                ).getTime()
                                let date = new Date(value).getTime()
                                if (date > t) {
                                    return callback(
                                        new Error('计量日期需小于到期日期！')
                                    )
                                } else {
                                    return callback()
                                }
                            }
                            callback()
                        },
                        trigger: 'change',
                    },
                ],
                expireTime: [
                    {
                        required: true,
                        validator: (rule, value, callback) => {
                            if (!value)
                                return callback(new Error('到期日期不能为空！'))
                            if (this.dialogForm.gaugeTime) {
                                let t = new Date(
                                    this.dialogForm.gaugeTime
                                ).getTime()
                                let date = new Date(value).getTime()
                                if (date > t) {
                                    return callback()
                                } else {
                                    return callback(
                                        new Error('到期日期需大于计量日期！')
                                    )
                                }
                            }
                            callback()
                        },
                        trigger: 'change',
                    },
                ],
            },
        }
    },
    methods: {
        resetValidate(val) {
            if (this.dialogForm.measuringCode === 'NA') {
                this.rules.gaugeTime = []
                this.rules.expireTime = []
            } else {
                this.rules.gaugeTime = [
                    {
                        required: true,
                        validator: (rule, value, callback) => {
                            if (!value)
                                return callback(new Error('计量日期不能为空！'))
                            if (this.dialogForm.expireTime) {
                                let t = new Date(
                                    this.dialogForm.expireTime
                                ).getTime()
                                let date = new Date(value).getTime()
                                if (date > t) {
                                    return callback(
                                        new Error('计量日期需小于到期日期！')
                                    )
                                } else {
                                    return callback()
                                }
                            }
                            callback()
                        },
                        trigger: 'change',
                    },
                ]
                this.rules.expireTime = [
                    {
                        required: true,
                        validator: (rule, value, callback) => {
                            if (!value)
                                return callback(new Error('到期日期不能为空！'))
                            if (this.dialogForm.gaugeTime) {
                                let t = new Date(
                                    this.dialogForm.gaugeTime
                                ).getTime()
                                let date = new Date(value).getTime()
                                if (date > t) {
                                    return callback()
                                } else {
                                    return callback(
                                        new Error('到期日期需大于计量日期！')
                                    )
                                }
                            }
                            callback()
                        },
                        trigger: 'change',
                    },
                ]
            }
            this.$refs.detailForm.clearValidate()
        },
        /** 发起提交 */
        submitForm: function () {
            this.dialogForm
            this.$refs.detailForm.validate((valid) => {
                let action = this.type == 1 ? addGauge : modGauge
                let fileId = []
                this.picFileList.forEach((io) => {
                    fileId.push(io.id || (io.response && io.response.data.id))
                })
                if (valid) {
                    this.loading = true
                    action({
                        ...this.dialogForm,
                        fileId: fileId.join(','),
                    })
                        .then((res) => {
                            this.loading = false
                            if (res.code == 200) {
                                this.$emit('refresh')
                                this.$modal.msgSuccess('操作成功!')
                                this.$emit('update:visible', false)
                            } else {
                                this.loading = false
                                this.$modal.msgError(res.msg)
                            }
                        })
                        .catch((err) => {
                            this.loading = false
                        })
                }
            })
        },
        geFileByBiz() {
            geFileByBiz({ bizId: this.dialogForm.id }).then((res) => {
                let picList = []
                res.data.forEach((io) => {
                    if (io.bizType === 'UPLOAD_FILE') {
                        picList.push(io)
                    }
                })
                this.picList = picList
            })
        },
        picChange(fileList) {
            this.picFileList = fileList
        },
        handleClose(done) {
            this.dialogForm = {}
            this.picFileList = []
            this.resetForm('detailForm')
            try {
                this.$refs['uploadFile'].handleRemove()
            } catch (error) {}
            this.$emit('update:visible', false)
            this.$emit('resetVisbleForm', false)
        },
        //设备模糊查询
        deviceRemoteMethod(val, cb) {
            console.log(val)
            listAllGaugeMessage({ deviceName: val }).then((res) => {
                this.deviceOptions = res.data.map((i) => i.deviceName)
                cb(res.data)
            })
        },
        handleDeviceSelect(e) {
            this.dialogForm.deviceName = e.deviceName
            this.dialogForm.gaugeType = e.gaugeType
            this.$refs.deviceName.$emit('el.form.blur')
        },
        handleDeviceBlur(e) {
            const { deviceOptions, dialogForm } = this
            if (!deviceOptions.includes(dialogForm.deviceName)) {
                this.dialogForm.deviceName = ''
            }
        },
        //工厂模糊查询
        factoryRemoteMethod(val, cb) {
            listALLFactory({ plantName: val }).then((res) => {
                this.factoryOptions = res.data.map((i) => i.deviceName)
                cb(res.data)
            })
        },
        handleFactorySelect(e) {
            this.dialogForm.factoryName = e.plantName
            this.dialogForm.factoryCode = e.plantCode
            this.$refs.factoryName.$emit('el.form.blur')
        },
        handleFactoryBlur(e) {
            const { factoryOptions, dialogForm } = this
            if (!factoryOptions.includes(dialogForm.factoryName)) {
                this.dialogForm.factoryName = ''
            }
        },
        handleGaugeTime(e) {
            const self = this
            const { dialogForm } = self
            this.expireTimeOptions = {
                disabledDate(time) {
                    let res = false
                    if (dialogForm) {
                        const { gaugeTime, expireTime } = dialogForm
                        if (gaugeTime) {
                            res = time.getTime() < new Date(gaugeTime).getTime()
                        }
                    }
                    return res
                },
            }
        },
        handleExpireTime(e) {
            const today = new Date().getTime()
            const val = new Date(e).getTime()
            if (val > today) {
                this.dialogForm.remDay = ~~(
                    (val - today) /
                    1000 /
                    60 /
                    60 /
                    24
                ).toFixed(1)
                console.log(this.dialogForm.remDay)
            } else {
                this.dialogForm.remDay = 0
            }
            this.$forceUpdate()
        },
        handleRespDept(e) {
            this.$set(this.dialogForm, 'respDept', e.name)
            this.$refs.detailForm.validateField('respDept')
            this.dialogForm.respUser = { id: '0', name: '' }
            this.$set(this.dialogForm, 'respName', '')
            this.$forceUpdate()
        },
        handleRespName(e) {
            this.$set(this.dialogForm, 'respName', e.userName)
            this.$refs.detailForm.validateField('respName')
            this.dialogForm.respDeptment = { id: e.deptId, name: e.deptName }
            this.$set(this.dialogForm, 'respDept', e.deptName)
            this.$refs.detailForm.validateField('respDept')
            this.$forceUpdate()
        },
        handleEmployName(e) {
            this.$set(this.dialogForm, 'employName', e.userName)
            this.$refs.detailForm.validateField('employName')

            this.$forceUpdate()
        },

        handleFile(e) {
            this.dialogForm.fileIds = e
        },
    },
}
</script>

<style scoped>
::v-deep .el-popper[x-placement^='bottom'] {
    width: 260px !important;
}
</style>
